<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Adscate extends Admin_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->model('admin/'. __CLASS__ .'_model', 'model');
	}

	public function index() {
		$data = [];
		$data['lists'] = $this->model->get_lists();

		$data['nav'] = $this->get_nav();
		$this->load->view($this->view, $data);
	}

	//显示添加模板
	public function add() {
		$data = [];

		//添加
		if ('POST' == $this->input->server('REQUEST_METHOD')) {
			$lang = config_item('lang');
			$insert_id = $this->model->insert();
			if (empty($insert_id)) {
				$this->error([
					'url' => $this->input->server('HTTP_REFERER'),
					'message' => $this->model->error,
				]);
			}
			$this->success([
				'url' => site_url('admin/adscate/add'),
				'message' => $lang['action_success'],
			]);
		}

		$data['nav'] = $this->get_nav();

		$this->load->view($this->view, $data);
	}

	//显示编辑模板
	public function edit($id = 0) {
		$data = [];
		$lang = config_item('lang');
		
		$id = (int) $this->uri->segment(4, 0);
		if (empty($id)) {
			$this->error([
				'url' => site_url('admin/adscate/index'),
				'message' => $lang['method_illegal'],
			]);
		}

		$where = ['id' => $id];
		//编辑
		if ('POST' == $this->input->server('REQUEST_METHOD')) {
			$affected_rows = $this->model->update($where);
			if (empty($affected_rows)) {
				$this->error([
					'url' => $this->input->server('HTTP_REFERER'),
					'message' => $lang['action_error'],
				]);
			}
			$this->success([
				'url' => site_url('admin/adscate/index'),
				'message' => $lang['action_success'],
			]);
		}

		$data['row'] = $this->model->get_one($where);
		if (empty($data['row'])) {
			$this->error([
				'url' => site_url('admin/adscate/index'),
				'message' => $lang['data_illegal'],
			]);
		}

		$data['nav'] = $this->get_nav();

		$this->load->view($this->view, $data);
	}

	//删除
	public function del($id = 0) {
		$lang = config_item('lang');
		$id = (int) $this->uri->segment(4, 0);
		if (empty($id)) {
			$this->error([
				'url' => site_url('admin/adscate/index'),
				'message' => $lang['method_illegal'],
			]);
		}

		$where = ['id' => $id];
		$affected_rows = $this->model->delete($where);
		if (empty($affected_rows)) {
			$this->error([
				'url' => site_url('admin/adscate/index'),
				'message' => $lang['action_error'],
			]);
		}
		$this->load->model('admin/Ads_model');
		$this->Ads_model->delete(['adscate_id' => $id]);
		redirect('admin/adscate/index');
	}
}
